﻿using System;
using System.Web.Mvc;
using Actya.Core.Security;
using Actya.Core.Infrastructure;

namespace Actya.Web.Filters
{
	public class CmsAuthorizationFilter : ActionFilterAttribute, IAuthorizationFilter
	{
		public void OnAuthorization(AuthorizationContext filterContext)
		{
			var membershipService = DependencyResolver.Current.GetService<IMembershipService>();
			string currentUsername = null;

			// Check if user is authenticated already. If so, try to replace the identity with the cms identity.
			if (filterContext.HttpContext.User != null && filterContext.HttpContext.User.Identity.IsAuthenticated)
			{
				currentUsername = filterContext.HttpContext.User.Identity.Name;
			}
			if (!String.IsNullOrEmpty(currentUsername))
			{
				var cmsUser = membershipService.GetUserByUsername(currentUsername, true);
				if (cmsUser != null)
				{
					cmsUser.IsAuthenticated = true;
					filterContext.HttpContext.User = cmsUser; 
				}
			}
		}
	}
}